<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-05-23 09:57:07
-->
<template>
  <BaseDialog v-model="dialogVisible" :title="$t('public.detail')" width="850px" :before-close="handleClose">
    <div v-loading="viewLoading">
      <el-descriptions :column="2" border :label-width="140">
        <el-descriptions-item width="200">
          <template #label>{{ $t('travelAgency.templateName') }}</template>
          {{ formData.name || '--' }}
        </el-descriptions-item>
        <el-descriptions-item width="200">
          <template #label>{{ $t('travelAgency.tripDays') }}</template>
          {{ formData.tripDays || '--' }}
        </el-descriptions-item>
        <el-descriptions-item width="200">
          <template #label>{{
            $t('travelAgency.defaultPersonCount')
            }}</template>
          {{ formData.peopleCount || '--' }}
        </el-descriptions-item>
        <el-descriptions-item width="200">
          <template #label>{{ $t('travelAgency.applicableAge') }}</template>
          {{ formData.ageMin }} - {{ formData.ageMax }}
        </el-descriptions-item>
      </el-descriptions>
      <BaseTable ref="refContentTable" :data="tableData" show-summary :summary-method="getSummaries"
        :span-method="arraySpanMethod" max-height="calc(100vh - 272px)" row-key="id" style="margin-top: 10px">
        <TableColumn prop="day" :label="$t('travelAgency.days')" :column-width="routeColumnWidth.day">
          <template #default="{ row }">
            <span>{{
              g_t('travelAgency.dayI', {
              i: g_nzhcn.encodeS(row.day)
              })
              }}</span>
          </template>
        </TableColumn>
        <TableColumn prop="address" :label="$t('travelAgency.location')" :column-width="routeColumnWidth.address" />
        <TableColumn prop="name" :label="$t('travelAgency.project')" :column-width="routeColumnWidth.name" />
        <TableColumn prop="type" :label="$t('travelAgency.type')" :column-width="routeColumnWidth.type">
          <template #default="{ row }">
            <span>{{
              g_options.getOptionText(
              g_options.costItemTypeOptions,
              row.type,
              '--'
              )
              }}</span>
          </template>
        </TableColumn>
        <TableColumn prop="count" min-width="80" :label="$t('travelAgency.quantity')"
          :column-width="routeColumnWidth.count" />
        <TableColumn prop="price" min-width="80" :label="$t('hotel.unitPrice')"
          :column-width="routeColumnWidth.price" />
        <TableColumn prop="exchangeRate" min-width="80" :label="$t('travelAgency.exchangeRate')"
          :column-width="routeColumnWidth.exchangeRate" />
        <TableColumn prop="totalPrice" min-width="80" :label="$t('travelAgency.totalPrice')"
          :column-width="routeColumnWidth.totalPrice" />
        <TableColumn prop="perCapitaPrice" min-width="150" :label="$t('travelAgency.perCapitaPrice')"
          :column-width="routeColumnWidth.perCapitaPrice" />
      </BaseTable>
    </div>
    <template #footer>
      <div class="detail-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.close')
          }}</el-button>
      </div>
    </template>
  </BaseDialog>
</template>

<script setup>
const props = defineProps({
  id: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const viewLoading = ref(false)
const formData = ref({
  name: '',
  peopleCount: '',
  ageMin: '',
  ageMax: '',
  itemList: []
})
const refContentTable = ref(null)
const routeColumnWidth = ref({})
const tableData = computed(() => {
  return formData.value.itemList.map(item => {
    const totalPrice = g_utils.getFloat(
      item.count * item.price * item.exchangeRate
    )
    return {
      ...item,
      totalPrice,
      perCapitaPrice: formData.value.peopleCount
        ? g_utils.getFloat(totalPrice / formData.value.peopleCount)
        : '--'
    }
  })
})

watch(
  () => tableData.value,
  nv => {
    setTimeout(() => {
      useTableColumnWidth({
        refTable: refContentTable.value
      }).getTableColumnWidth(data => {
        routeColumnWidth.value = data
      })
    })
  },
  {
    immediate: true,
    deep: true
  }
)

onMounted(() => {
  getFormData()
})

const getFormData = () => {
  viewLoading.value = true
  g_api.travelAgency
    .apiCalculatorDetail({ templateId: props.id })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        formData.value = data
      }
      console.log('formData.value', formData.value)
    })
    .finally(_ => {
      viewLoading.value = false
    })
}

const handleClose = () => {
  dialogVisible.value = false
}

const getSummaries = param => {
  // console.log('getSummaries', param)
  const result = tableData.value.reduce(
    (acc, curr) => {
      acc.totalPrice += curr.totalPrice * 1
      if (curr.type + '' === '1' || curr.type + '' === '4') {
        acc.carGuidePrice += curr.totalPrice * 1
      } else if (curr.type + '' === '2') {
        acc.mealPrice += curr.totalPrice * 1
      } else if (curr.type + '' === '3') {
        acc.roomPrice += curr.totalPrice * 1
      }
      return acc
    },
    { totalPrice: 0, carGuidePrice: 0, mealPrice: 0, roomPrice: 0 }
  )
  console.log('getSummaries-result', result)
  const showPrice = data => {
    return formData.value.peopleCount
      ? g_utils.getFloat(data / formData.value.peopleCount)
      : '--'
  }
  formData.value.totalPrice = g_utils.getFloat(result.totalPrice)
  formData.value.perPersonPrice = showPrice(result.totalPrice)
  return [
    `${g_t('travelAgency.totalPrice')}：${formData.value.totalPrice}`,
    '',
    `${g_t('travelAgency.perCapitaTotalPrice')}：${formData.value.perPersonPrice
    }`,
    '',
    `${g_t('travelAgency.perCapitaVehicleGuidePrice')}：${showPrice(
      result.roomPrice
    )}`,
    '',
    `${g_t('travelAgency.perCapitaMealPrice')}：${showPrice(result.carGuidePrice)}`,
    '',
    `${g_t('travelAgency.perCapitaRoomPrice')}：${showPrice(result.mealPrice)}`,
    ''
  ]
}

const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // console.log(
  //   'row, column, rowIndex, columnIndex',
  //   row,
  //   column,
  //   rowIndex,
  //   columnIndex
  // )
  nextTick(() => {
    if (refContentTable.value.$el) {
      const current = refContentTable.value.$el
        .querySelector('.el-table__footer-wrapper')
        .querySelector('.el-table__footer')
      const cell = current.rows[0].cells
      // 定义要合并的列规则：起始索引 & 合并个数
      const mergeRules = [
        { index: 0, span: 2 }, // 合并第 0 列，跨 2 列
        { index: 2, span: 2 },
        { index: 4, span: 2 },
        { index: 6, span: 2 },
        { index: 8, span: 2 }
      ]

      // 执行合并与样式设置
      mergeRules.forEach(rule => {
        const { index, span } = rule
        if (cell[index]) {
          cell[index].colSpan = span
          cell[index].style.textAlign = 'center'

          // 隐藏后续被合并的单元格
          for (let i = 1; i < span; i++) {
            if (cell[index + i]) {
              cell[index + i].style.display = 'none'
            }
          }
        }
      })
      // 修改单元格的样式
      for (let i = 0; i < cell.length; i++) {
        cell[i].style.color = i === 0 ? '#6fba2c' : '#333'
      }
    }
  })
}
</script>

<style scoped lang="scss"></style>
